package com.hcloud.libupload.utils

import android.util.Base64
import java.nio.charset.Charset
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

object AESBase64Util {
    private val skey: String? = "KrEj3WxoKitfRfkC"
    private const val siv = "4KewNGDcHa3Q4cTX"
    fun encrypt(sSrc: String): String {
        return try {
            if (skey == null) {
                print("Key为空null")
                return ""
            }
            // 判断Key是否为16位
            val raw = skey.toByteArray(charset("utf-8"))
            val skeySpec =
                SecretKeySpec(raw, "AES")
            val cipher =
                Cipher.getInstance("AES/CBC/PKCS5Padding") //"算法/模式/补码方式"
            //CBC模式需要配置偏移量，设置一个向量，达到密码唯一性，增加加密算法的强度
            val iv =
                IvParameterSpec(siv.toByteArray())
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv)
            val encrypted = cipher.doFinal(sSrc.toByteArray(charset("utf-8")))
            String(Base64.encode(encrypted, Base64.DEFAULT))
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    fun decrypt(sSrc: String): String {
        return try {
            // 判断Key是否正确
            if (skey == null) {
                print("Key为空null")
                return ""
            }
            // 判断Key是否为16位
            if (skey.length != 16) {
                print("Key长度不是16位")
                return ""
            }
            val raw = skey.toByteArray(charset("utf-8"))
            val skeySpec =
                SecretKeySpec(raw, "AES")
            val cipher =
                Cipher.getInstance("AES/CBC/PKCS5Padding")
            //CBC模式需要配置偏移量，设置这个后，不会出来同一个明文加密为同一个密文的问题，达到密文唯一性
            val iv = IvParameterSpec(siv.toByteArray())
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv)
            val encrypted1: ByteArray =
                Base64.decode(
                    sSrc,
                    Base64.DEFAULT
                )
            val original = cipher.doFinal(encrypted1)
            String(original, Charset.forName("utf-8"))
        } catch (ex: Exception) {
            ex.printStackTrace()
            ""
        }
    }
}